package com.cloudsea.yunhaiserver.task;

import cn.hutool.core.lang.Snowflake;
import com.cloudsea.yunhaianalysis.entity.SalesAnalysis;
import com.cloudsea.yunhaianalysis.mapper.AnalysisMapper;
import com.cloudsea.yunhaianalysis.mapper.SalesAnalysisMapper;
import com.cloudsea.yunhaianalysis.service.ExternalApiService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;

@Component
public class ETLTask {

    private static final Logger log = LoggerFactory.getLogger(ETLTask.class);

    @Autowired private AnalysisMapper analysisMapper;
    @Autowired private SalesAnalysisMapper salesAnalysisMapper;
    @Autowired private ExternalApiService externalApiService;
    @Autowired private Snowflake snowflake;

    /**
     * 每日ETL（数据提取、转换、加载）任务
     * 在每天的凌晨 01:15:00 自动执行
     */
    @Scheduled(cron = "0 15 1 * * ?")
    public void runDailyETL() {
        // 确定要处理的目标日期：昨天
        LocalDate yesterday = LocalDate.now().minusDays(1);
        log.info("开始执行日期为 [{}] 的每日ETL任务...", yesterday);

        // 步骤1: [Extract] - 聚合昨日的内部销售数据
        LocalDateTime startTime = yesterday.atStartOfDay();
        LocalDateTime endTime = yesterday.atTime(LocalTime.MAX);
        List<SalesAnalysis> dailySales = analysisMapper.summarizeDailySales(startTime, endTime);

        if (dailySales.isEmpty()) {
            log.info("昨日无已支付订单，ETL任务结束。");
            return;
        }

        // 步骤2: 遍历每一条销售记录，为其 [Transform & Load] 补充外部特征
        for (SalesAnalysis sale : dailySales) {
            sale.setId(snowflake.nextId());
            sale.setRecordDate(yesterday);
            sale.setDayOfWeek(yesterday.getDayOfWeek().getValue());

            // 2a. 【核心修正】调用获取【历史】天气的方法
            Map<String, String> weatherInfo = externalApiService.getHistoricalWeather(yesterday);
            sale.setWeatherDay(weatherInfo.get("weatherDay"));
            sale.setWeatherNight(weatherInfo.get("weatherNight"));
            sale.setMaxTemperature(Integer.parseInt(weatherInfo.get("maxTemp")));
            sale.setMinTemperature(Integer.parseInt(weatherInfo.get("minTemp")));
            sale.setAvgHumidity(Integer.parseInt(weatherInfo.get("avgHumidity")));
            sale.setTotalPrecip(new BigDecimal(weatherInfo.get("totalPrecip")));

            // 2b. 获取并填充节假日信息
            Map<String, Object> holidayInfo = externalApiService.getHolidayInfo(yesterday);
            sale.setIsHoliday((Boolean) holidayInfo.get("isHoliday"));
            sale.setHolidayName((String) holidayInfo.get("holidayName"));

            // 步骤3: [Load] - 将处理好的完整数据存入分析表
            // (未来可优化为批量插入)
            salesAnalysisMapper.insert(sale);
        }
        log.info("成功处理并加载了 [{}] 条销售分析数据。", dailySales.size());
    }
}